# @Version        : 1.0
# @Update Time    : 2025/10/15 00:00
# @File           : context.py
# @IDE            : PyCharm
# @Desc           : 认证上下文管理器
import contextvars
from typing import Optional

from fastapi import Request

from authx.utils.singleton import Singleton

_current_request: contextvars.ContextVar[Optional[Request]] = contextvars.ContextVar(
    "current_request", default=None
)
_current_token: contextvars.ContextVar[Optional[str]] = contextvars.ContextVar(
    "current_token", default=None
)


class AuthContextManager(metaclass=Singleton):
    @staticmethod
    def set_current_request(request: Request):
        _current_request.set(request)

    @staticmethod
    def get_request() -> Optional[Request]:
        return _current_request.get()

    @staticmethod
    def set_current_token(token: str):
        _current_token.set(token)

    @staticmethod
    def get_current_token() -> Optional[str]:
        return _current_token.get()

    @staticmethod
    def get_storage() -> dict:
        request = _current_request.get()
        if request is None:
            # 如果没有当前请求，返回空字典
            return {}
        if not hasattr(request.state, "sa_token_storage"):
            request.state.sa_token_storage = {}
        return request.state.sa_token_storage

    @staticmethod
    def setup_context(request: Request):
        """设置请求上下文"""
        # 设置当前请求
        _current_request.set(request)

    @staticmethod
    def cleanup_context():
        """清理请求上下文"""
        _current_request.set(None)
        _current_token.set(None)
